package google.sites.model.commands.attachments;

import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.sites.AttachmentEntry;
import com.google.gdata.util.ServiceException;
import dev.tools.design.patterns.command.Command;
import dev.tools.design.patterns.command.CommandException;
import google.sites.model.Model;

import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 04-10-2013
 * Time: 14:36
 */
public class UpdateAttachment extends Command {

    private final AttachmentEntry entry;
    private File newFile;
    private String newTitle;
    private String newDescription;

    public UpdateAttachment(AttachmentEntry entry) {
        this.entry = entry;
    }

    @Override
    protected void protectedExecute() throws CommandException {
        try {
            if (newFile == null) {
                entry.setTitle(new PlainTextConstruct(newTitle));
                entry.setSummary(new PlainTextConstruct(newDescription));

                setResult(entry.update());

                return;
            }

            entry.setMediaSource(new MediaFileSource(newFile, Model.INSTANCE.mediaTypes.getContentType(newFile)));

            if (newTitle != null) {
                entry.setTitle(new PlainTextConstruct(newTitle));
            }
            if (newDescription != null) {
                entry.setSummary(new PlainTextConstruct(newDescription));
            }

            setResult(entry.updateMedia(true));
        } catch (IOException | ServiceException e) {
            throw new CommandException(e);
        }
    }

    public UpdateAttachment setNewFile(File newFile) {
        this.newFile = newFile;
        return this;
    }

    public UpdateAttachment setNewTitle(String newTitle) {
        this.newTitle = newTitle;
        return this;
    }

    public UpdateAttachment setNewDescription(String newDescription) {
        this.newDescription = newDescription;
        return this;
    }
}
